package edu.tgc.security;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

import edu.tgc.entity.system.SysUser;

public class SessionUser implements UserDetails, CredentialsContainer {

    private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
        private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

        @Override
        public int compare(GrantedAuthority g1, GrantedAuthority g2) {
            // Neither should ever be null as each entry is checked before adding it to
            // the set.
            // If the authority is null, it is a custom authority and should precede
            // others.
            if (g2.getAuthority() == null) {
                return -1;
            }
            if (g1.getAuthority() == null) {
                return 1;
            }
            return g1.getAuthority().compareTo(g2.getAuthority());
        }
    }

    private static final long serialVersionUID = -4889009051807985791L;

    private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
        Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
        // Ensure array iteration order is predictable (as per
        // UserDetails.getAuthorities() contract and SEC-717)
        SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<>(new AuthorityComparator());
        for (GrantedAuthority grantedAuthority : authorities) {
            Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
            sortedAuthorities.add(grantedAuthority);
        }
        return sortedAuthorities;
    }

    protected final boolean accountNonExpired;
    protected final boolean accountNonLocked;
    protected final Set<GrantedAuthority> authorities;
    protected final boolean credentialsNonExpired;
    protected SysUser delegate;
    protected final boolean enabled;
    // ~ Instance fields
    // ================================================================================================
    protected UUID id;
    protected String name;

    protected String password;

    protected final String username;

    public SessionUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, username, true, true, true, true, authorities);
    }

    public SessionUser(String username, String password, String... authorities) {
        this(username, password, username, authorities);
    }

    public SessionUser(String username, String password, String name, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        this.username = username;
        this.password = password;
        this.name = name;
        this.enabled = enabled;
        this.accountNonExpired = accountNonExpired;
        this.credentialsNonExpired = credentialsNonExpired;
        this.accountNonLocked = accountNonLocked;
        this.authorities = Collections.unmodifiableSet(SessionUser.sortAuthorities(authorities));
    }

    public SessionUser(String username, String password, String name, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, name, true, true, true, true, authorities);
    }

    public SessionUser(String username, String password, String name, String... authorities) {
        this(username, password, name, true, true, true, true, Collections.unmodifiableSet(SessionUser.sortAuthorities(AuthorityUtils.createAuthorityList(authorities))));
    }

    public SessionUser(SysUser user, Set<? extends GrantedAuthority> authorities) {
        this(user.getUsername(), user.getPassword(), user.getCade().getName(), user.getEnabled(), true, true, true, authorities);
        this.id = user.getId();
    }

    @Override
    public void eraseCredentials() {
        this.password = null;
    }

    @Override
    public Set<GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    public UUID getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
